#!/usr/bin/env python

import os
import urllib
import json

from google.appengine.api import users
from google.appengine.ext import ndb

import jinja2
import webapp2

from webapp2_extras import sessions
from webapp2_extras import config as webapp2_config



class BaseRequestHandler(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(BaseRequestHandler, self).__init__(*args, **kwargs)
        self.user = users.get_current_user()
        self.template_values = {
            'logged_in_user' : users.get_current_user(),
            'x' : users.create_login_url(self.request.uri),
            'logout_url' : users.create_logout_url('/'),
            'login_url' : users.create_login_url('/'),
            'a' : args,
            'b' : kwargs
        }

        #app.config = webapp2_config.Config(my_config)
        pass
        
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)
 
        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)
    
    def isAnonymous(self):
        return self.session["ACCOUNT_ID"] == ""
        
    def anonymousRedirect(self):
        if self.session["ACCOUNT_ID"] == "":
            #self.response.write(self.request)
            # self.response.write("<p>path: " + self.request.path + "</p>")
            # self.response.write("<p>path_info: " + self.request.path_info  + "</p>")
            # self.response.write("<p>path_url: " + self.request.path_url + "</p>")
            # self.response.write("<p>path_qs: " + self.request.path_qs + "</p>")
            # self.response.write("<p>application_url: " + self.request.application_url + "</p>")
            # self.response.write("<p>host_url: " + self.request.host_url + "</p>")
            # self.response.write("<p>path_url: " + self.request.path_url + "</p>")
            # #self.response.write("<p>relative_url: " + self.request.relative_url + "</p>")
            # self.response.write("<p>url: " + self.request.url + "</p>")
            self.redirect("/user/login?dst={0}".format(self.request.path_qs))
            pass
    
    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        session = self.session_store.get_session(name="APP_SESSION", max_age=360, backend='securecookie')
        #add some default values:
        if not session.get("ACCOUNT_ID"):
            session["ACCOUNT_ID"] = ""
        return session
        
    def get_config(self):
        config = {}
        config['webapp2_extras.sessions'] = {
            'secret_key': 'some-secret-key',
        }